package com.heima.article.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.heima.article.dao.ApArticleDao;
import com.heima.article.service.ApArticleFreemarkerService;
import com.heima.file.MinIOTemplate;
import com.heima.model.article.entity.ApArticle;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class ArticleFreemarkerServiceImpl implements ApArticleFreemarkerService {
    @Resource
    private Configuration configuration;
    @Resource
    private MinIOTemplate minIOTemplate;
    @Resource
    private ApArticleDao apArticleDao;


    @Override
    public String buildArticle2Minio(Long id, String content) throws IOException, TemplateException {
        if (StringUtils.isBlank(content)) {
            return null;
        }
        //2. 使用freemarker生成静态HTML页面
        //2.1 定义数据模型
        Map<String,Object> dataModel=new HashMap<>();
        dataModel.put("content",JSON.parseArray(content));
        //2.2 加载模板
        Template template = configuration.getTemplate("article.ftl");
        //2.3 生成页面
        StringWriter writer = new StringWriter();
        template.process(dataModel,writer);
        //3. 将静态HTML页面上传到minio
        ByteArrayInputStream is= new ByteArrayInputStream(writer.toString().getBytes());
        String url = minIOTemplate.uploadHtmlFile("", id + ".html", is);
        System.out.println("url = " + url);
        //4. 修改文章表, 回填静态URL地址
        ApArticle apArticle = new ApArticle();
        apArticle.setId(id);
        apArticle.setStaticUrl(url);
        apArticleDao.update(apArticle);
        return url;
    }
}
